package com.example.anday3.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.anday3.R;

import java.util.List;

public class StrListAdapter extends ArrayAdapter<String> {
    private final List<String> mData;
    public StrListAdapter(@NonNull Context context,  @NonNull List<String> objects) {
        super(context, R.layout.item, objects);
        this.mData=objects;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
       if(convertView==null){
           convertView= LayoutInflater.from(getContext()).inflate(R.layout.item,parent,false);
       }
     String item=  getItem(position);
       TextView textView=convertView.findViewById(R.id.txtitem);
       Button button=convertView.findViewById(R.id.delbtn);
       Button button2=convertView.findViewById(R.id.xg);

       textView.setText(item);
       button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               remove(item);
               notifyDataSetChanged();
           }
       });
       button2.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
               final EditText input = new EditText(getContext());
               input.setText(item);
               builder.setView(input);
               final int currentPosition = position;
               // 2. 确认修改
               builder.setPositiveButton("确认", (dialog, which) -> {
                   String newText = input.getText().toString();
                   // 更新数据源
                    mData.set(currentPosition,newText);
                   // 刷新列表
                   notifyDataSetChanged();
               });

               builder.setNegativeButton("取消", null);
               builder.show();
           }});


       return convertView;
    }
}
